﻿using MB.RuleBase.Common;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WoChu.Autorun.Base.Dao;
using WoChu.Autorun.Base.Model;
using WoChu.Autorun.Base.Util;
using Newtonsoft.Json;

namespace WoChu.Autorun.Logic
{
    public class WCS_TO_WMSBase
    {
        private static WCS_TO_WMSBase _NewInstance = new WCS_TO_WMSBase();

        public static WCS_TO_WMSBase NewInstance
        {
            get
            {
                if (_NewInstance == null)
                {
                    _NewInstance = new WCS_TO_WMSBase();
                }

                return _NewInstance;
            }
        }

        public ResultModel getWCS_TO_WMSlist(string BoxNO, int flag = 0)
        {

            WCS_WMSDao dao = new WCS_WMSDao();
            //根据订单号获取未处理的绑定周转箱反馈表、
            try 
	        {
                List<WCS_TO_WMS> listUnDeal = dao.GetWCS_TO_WMSlistByBox(BoxNO, 0);
                 return new ResultModel { RESULT = "success", MESSAGE = "获取订单实捡信息成功", DATA = listUnDeal };
	        }
	        catch (Exception ex)
	        {
                return new ResultModel { RESULT = "failed", MESSAGE = "获取订单实捡信息失败："+ex.Message, DATA = null };
	        }
        }

        /// <summary>
        /// 更新erp订单实捡数量以及实际拣货时间等备注信息，病更新wcs_to_wms的flag，记录wcs_to_wms历史
        /// </summary>
        /// <param name="SyncCount"></param>
        /// <param name="OrderNO"></param>
        /// <returns></returns>
        public ResultModel syncWCS_TO_WMS_tohistory(out int SyncCount,string OrderNO)
        {
            bool _result = false;
            string _message="";
            SyncCount = 0;
            var oracle = new MB.RuleBase.BulkCopy.SimulatedOracleHelper();
            var db = MB.Orm.Persistence.DatabaseHelper.CreateDatabase();
            var cn = oracle.CreateOracleConnection(db.ConnectionString);
            System.Data.Common.DbTransaction tran = null;
            try
            {
                // 打开数据连接
                cn.Open();
                tran = cn.BeginTransaction();

                WCS_WMSDao dao = new WCS_WMSDao();
                //根据订单号获取未处理的绑定周转箱反馈表
                List<WCS_TO_WMS> listUnDeal = dao.GetWCS_TO_WMSlist(OrderNO,0);

                SyncCount = listUnDeal.Count;
                foreach (WCS_TO_WMS model in listUnDeal)
                {

                    dao.UpdateWCS_TO_WMS(tran, model.DETAILNO, int.Parse(Consts.WCS_TO_WMS_DealedFlag));
                    dao.UpdateSaleItemQTY(tran, model.PQTY, model.ITEMCODE, model.ORDERNO);
                }
                dao.InsertWCSTOWMShistory(tran, listUnDeal);

                _result = true;
                if (_result)
                {
                    tran.Commit();
                }
                else
                {
                    tran.Rollback();
                }
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                tran.Rollback();
                _message =ex.Message;
                _result = false;
            }
            finally
            {
                if (tran != null) tran.Dispose();
                if (cn != null) cn.Close();
                if (cn != null) cn.Dispose();
            }

            //WCS_WMSDao dao = new WCS_WMSDao();
            ////获取未处理的绑定周转箱反馈表
            //List<WCS_TO_WMS> listUnDeal = dao.GetWCS_TO_WMSlist();
            //foreach (WCS_TO_WMS model in listUnDeal)
            //{
                
            //    dao.UpdateWCS_TO_WMS(model.DETAILNO,int.Parse(Consts.WCS_TO_WMS_DealedFlag));
            //    dao.UpdateSaleItemQTY(model.PQTY, model.ITEMCODE, model.ORDERNO);
            //}
            //dao.InsertWCSTOWMShistory(listUnDeal);

            if (_result)
                return new ResultModel { RESULT = "success", MESSAGE = "wcs_to_wms以及erp相关信息更新成功！", DATA = null };
            else
                return new ResultModel { RESULT = "failed", MESSAGE = "wcs_to_wms以及erp相关信息更新失败！：" + _message, DATA = null };
        }

        /// <summary>
        /// 周转箱复核发下泡沫箱
        /// </summary>
        /// <param name="DeatilNO"></param>
        /// <param name="OrderNO"></param>
        /// <param name="UserID"></param>
        /// <param name="UserName"></param>
        /// <param name="FboxNO">可以绑定泡沫箱</param>
        /// <returns></returns>
        public ResultModel Sendtask(int DetailNO, string OrderNO, int UserID, string UserName, string CheckLocation, List<string> FboxNO)
        {
            bool _result = false;
            string _message = "";
            WCS_WMSDao dao = new WCS_WMSDao();
            var oracle = new MB.RuleBase.BulkCopy.SimulatedOracleHelper();
            var db = MB.Orm.Persistence.DatabaseHelper.CreateDatabase();
            var cn = oracle.CreateOracleConnection(db.ConnectionString);
            System.Data.Common.DbTransaction tran = null;
            //using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required))
            //{
            try
            {
                //查询泡沫箱是否已绑定
                foreach (string item in FboxNO)
                {
                    WMS_TO_WCS_TASK task = dao.getWMS_TO_WCStask(item, 1);
                    if (task != null && !string.IsNullOrEmpty(task.ORDERNO))
                        return new ResultModel { RESULT = "failed", MESSAGE = string.Format("泡沫箱：{0} 已被绑定还未解绑！", item), DATA = null };
                }
                cn.Open();
                tran = cn.BeginTransaction();
                int flag = 0;
                string Exlocation = "";
                List<WCS_TO_WMS> list = dao.GetWCS_TO_WMSlist(OrderNO, flag);
                if (list == null || list.Count <= 0)
                {
                    return new ResultModel { RESULT = "failed", MESSAGE = string.Format("订单号：{0} 的捡货任务已完成，请勿重复提交！", OrderNO), DATA = null };
                }
                foreach (WCS_TO_WMS model in list)
                {
                    dao.UpdateWCS_TO_WMS(tran, model.DETAILNO, int.Parse(Consts.WCS_TO_WMS_DealedFlag));
                    dao.UpdateSaleItemQTY(tran, model.PQTY, model.ITEMCODE, model.ORDERNO);
                    dao.UpdateSaleItemQTY(tran, model.PTIME, model.BEGIN_DATE, model.BATCH_NO, model.LOCATION, model.ORDERNO);
                    Exlocation = model.EXLOCATION;
                }
                dao.InsertWCSTOWMShistory(tran, list);
                List<WMS_TO_WCS_TASK> tasklist = new List<WMS_TO_WCS_TASK>();

                foreach (string item in FboxNO)
                {
                    tasklist.Add(new WMS_TO_WCS_TASK { DETAILNO = DetailNO, ORDERNO = OrderNO, FBOXNO = item, EXLOCATION = Exlocation, OTHER1 = "1", STATUS = 0, CREATERID = UserID, CREATER = UserName, CHECK_LOCATION = CheckLocation });
                }
                dao.SendWMS_TO_WCStask(tran, tasklist);
                _result = true;
                if (_result)
                {
                    tran.Commit();
                    //ts.Complete();
                }
                else
                {
                    tran.Rollback();
                    //ts.Dispose();
                }
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                _message = ex.Message;
                tran.Rollback();
                //ts.Dispose();
                _result = false;
            }
            finally
            {
                if (tran != null) tran.Dispose();
                if (cn != null) cn.Close();
                if (cn != null) cn.Dispose();
            }
            //}
            if (_result)
                return new ResultModel { RESULT = "success", MESSAGE = "复核记录成功并下发泡沫箱任务！", DATA = null };
            else
                return new ResultModel { RESULT = "failed", MESSAGE = "复核记录成功并下发泡沫箱任务失败！：" + _message, DATA = null };
        }

        //判断当前订单是否可以重新绑定其他发货箱
        public ResultModel checkWMS_TO_WCStask(string OrderNO)
        {
            WCS_WMSDao dao = new WCS_WMSDao();
            //根据订单号获取未处理的绑定周转箱反馈表、
            try
            {
                List<WMS_TO_WCS_TASK> listTask = dao.getWMS_TO_WCStask(OrderNO);
                if (listTask == null || listTask.Count <= 0)
                {
                    return new ResultModel { RESULT = "success", MESSAGE = "当前订单未绑定泡沫箱发货", DATA = listTask };
                }
                else
                {
                    if (listTask[0].OTHER1 == "1")
                    {
                        string strFboxs = "";
                        foreach (WMS_TO_WCS_TASK item in listTask)
                        {
                            strFboxs += "【" + item.FBOXNO + "】";
                        }
                        return new ResultModel { RESULT = "success", MESSAGE = "当前订单已绑定发货箱："+ strFboxs, DATA = listTask };
                    }
                    else
                    {
                        return new ResultModel { RESULT = "failed", MESSAGE = "该订单已配送完毕，泡沫箱已解绑", DATA = listTask };
                    }
                }
                
            }
            catch (Exception ex)
            {
                return new ResultModel { RESULT = "failed", MESSAGE = "获取订单发货信息失败：" + ex.Message, DATA = null };
            }
        }

        public ResultModel UpdateWMS_TO_WCSTASKfboxs(string OrderNO, int UserID, string UserName, List<string> FboxNO)
        {
            bool _result = false;
            string _message = "";
            WCS_WMSDao dao = new WCS_WMSDao();
            var oracle = new MB.RuleBase.BulkCopy.SimulatedOracleHelper();
            var db = MB.Orm.Persistence.DatabaseHelper.CreateDatabase();
            var cn = oracle.CreateOracleConnection(db.ConnectionString);
            System.Data.Common.DbTransaction tran = null;
            try
            {
                //查询泡沫箱是否已绑定
                foreach (string item in FboxNO)
                {
                    WMS_TO_WCS_TASK task = dao.getWMS_TO_WCStask(item, 1);
                    if (task != null && !string.IsNullOrEmpty(task.ORDERNO))
                        return new ResultModel { RESULT = "failed", MESSAGE = string.Format("泡沫箱：{0} 已被绑定还未解绑！", item), DATA = null };
                }
                cn.Open();
                tran = cn.BeginTransaction();
                List<WMS_TO_WCS_TASK> tasklist = dao.getWMS_TO_WCStask(OrderNO);
                if (tasklist != null && tasklist.Count > 0)
                {
                    foreach (string item in FboxNO)
                    {
                        tasklist.Add(new WMS_TO_WCS_TASK { DETAILNO = 0, ORDERNO = OrderNO, FBOXNO = item, EXLOCATION = tasklist[0].EXLOCATION, OTHER1 = "1", STATUS = 0, CREATERID = UserID, CREATER = UserName, CHECK_LOCATION = tasklist[0].CHECK_LOCATION });
                    }
                }
                _result = dao.UpdateWMS_TO_WCStaskFLAGandOrderNO(tran, UserID, UserName, OrderNO) != 0;
                dao.SendWMS_TO_WCStask(tran, tasklist);
                _result = true && _result;
                if (_result)
                { tran.Commit(); }
                else
                { tran.Rollback(); }
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                _message = ex.Message;
                tran.Rollback();
                _result = false;
            }
            finally
            {
                if (tran != null) tran.Dispose();
                if (cn != null) cn.Close();
                if (cn != null) cn.Dispose();
            }
            if (_result)
                return new ResultModel { RESULT = "success", MESSAGE = "订单重新绑定发货箱成功！", DATA = null };
            else
                return new ResultModel { RESULT = "failed", MESSAGE = "订单重新绑定发货箱失败！：" + _message, DATA = null };
        }

        /// <summary>
        /// 复核产品异常
        /// </summary>
        /// <param name="DeatilNO"></param>
        /// <param name="OrderNO"></param>
        /// <param name="UserID"></param>
        /// <param name="UserName"></param>
        /// <param name="excepType">1-任务重复，2-任务取消，3拣货环节货物不够</param>
        /// <param name="boxNO"></param>
        /// <returns></returns>
        public ResultModel SendReCheckExcep(int DeatilNO, string OrderNO, int UserID, string UserName, int excepType,string excepDesc,  string boxNO,string CheckLocation)
        {
            bool _result = false;
            string _message = "";
            WCS_WMSDao dao = new WCS_WMSDao();
            var oracle = new MB.RuleBase.BulkCopy.SimulatedOracleHelper();
            var db = MB.Orm.Persistence.DatabaseHelper.CreateDatabase();
            var cn = oracle.CreateOracleConnection(db.ConnectionString);
            System.Data.Common.DbTransaction tran = null;
            try
            {
                cn.Open();
                tran = cn.BeginTransaction();
                switch (excepType) { 
                    case 1:
                        excepDesc = "任务重复==>"+ excepDesc;
                        break;
                    case 2:
                        excepDesc = "任务取消==>"+ excepDesc;
                        break;
                    case 3:
                        excepDesc = "拣货环节货物不够==>"+ excepDesc;
                        break;
                    default:
                        break;
                }
                dao.WriteRecheckExec(tran, DeatilNO, OrderNO, boxNO, excepType, excepDesc, UserName, "", CheckLocation);
                _result = true;
                if (_result)
                {
                    tran.Commit();
                }
                else
                {
                    tran.Rollback();
                }
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                tran.Rollback();
                _message = ex.Message;
                _result = false;
            }
            finally
            {
                if (tran != null) tran.Dispose();
                if (cn != null) cn.Close();
                if (cn != null) cn.Dispose();
            }
            if (_result)
                return new ResultModel { RESULT = "success", MESSAGE = "周转箱复核不合格记录成功！", DATA = null };
            else
                return new ResultModel { RESULT = "failed", MESSAGE = "周转箱复核不合格记录失败！："+_message, DATA = null };
        }

        /// <summary>
        /// //实捡数量与实物不符，重发拣货任务
        /// </summary>
        /// <returns></returns>
        //public ResultModel ReSendPickOrder(string OrderNO)
        //{
        //    bool _result = false;
        //    string _message = "";
        //    var oracle = new MB.RuleBase.BulkCopy.SimulatedOracleHelper();
        //    var db = MB.Orm.Persistence.DatabaseHelper.CreateDatabase();
        //    var cn = oracle.CreateOracleConnection(db.ConnectionString);
        //    System.Data.Common.DbTransaction tran = null;
        //    try
        //    {
        //        // 打开数据连接
        //        cn.Open();
        //        tran = cn.BeginTransaction();

        //        WCS_WMSDao dao = new WCS_WMSDao();
        //        //根据订单号获取未处理的绑定周转箱反馈表
        //        List<WCS_TO_WMS> listUnDeal = dao.GetWCS_TO_WMSlist(OrderNO, 0);
        //        List<WMS_TO_WCS> listRePick = new List<WMS_TO_WCS>();
        //        foreach (WCS_TO_WMS model in listUnDeal)
        //        {
        //            dao.UpdateWCS_TO_WMS(tran, model.DETAILNO, int.Parse(Consts.WCS_TO_WMS_ExcepFlag));//将该订单标记为异常作废单，下面重新下发拣货任务单
        //            WMS_TO_WCS tmModel = new WMS_TO_WCS()
        //            {
        //                ORDERNO = model.ORDERNO,
        //                BOXNO = model.BOXNO,
        //                EXLOCATION = model.EXLOCATION,
        //                LOCATION = model.LOCATION,
        //                ITEMCODE = model.ITEMCODE,
        //                ITEMNAME = model.ITEMNAME,
        //                QTY = model.QTY,
        //                REMARK1 = model.REMARK1,
        //                REMARK2 = model.REMARK2,
        //                BATCH_NO = model.BATCH_NO
        //            };
        //            listRePick.Add(tmModel);
        //        }
        //        dao.ReInsertWMS_TO_WCS(tran, listRePick);//重发任务
        //        _result = true;
        //        if (_result)
        //        {
        //            tran.Commit();
        //        }
        //        else
        //        {
        //            tran.Rollback();
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        MB.Util.TraceEx.Write(ex.Message);
        //        tran.Rollback();
        //        _message = ex.Message;
        //        _result = false;
        //    }
        //    finally
        //    {
        //        if (tran != null) tran.Dispose();
        //        if (cn != null) cn.Close();
        //        if (cn != null) cn.Dispose();
        //    }

        //    if (_result)
        //        return new ResultModel { RESULT = "success", MESSAGE = "wcs_to_wm拣货完成任务作废并重发拣货任务！", DATA = null };
        //    else
        //        return new ResultModel { RESULT = "failed", MESSAGE = "wcs_to_wm拣货完成任务作废并重发拣货任务！：" + _message, DATA = null };
        //}

        /// <summary>
        /// 周转箱解绑
        /// </summary>
        /// <param name="BoxNO"></param>
        /// <returns></returns>
        public ResultModel DebindBoxNO(string BoxNO, int UserID, string UserName)
        {
            bool _result = false;
            string _message = "";
            WCS_WMSDao dao = new WCS_WMSDao();
            var oracle = new MB.RuleBase.BulkCopy.SimulatedOracleHelper();
            var db = MB.Orm.Persistence.DatabaseHelper.CreateDatabase();
            var cn = oracle.CreateOracleConnection(db.ConnectionString);
            System.Data.Common.DbTransaction tran = null;
            try
            {
                cn.Open();
                tran = cn.BeginTransaction();
                WMS_TO_WCS_TASK task = dao.getWMS_TO_WCStask(BoxNO, 1);//已绑定订单的泡沫箱
                if (task != null)
                {
                    int _resultNO=dao.UpdateWMS_TO_WCS_TASKflag(tran, task.ORDERNO, task.FBOXNO, UserID, UserName);
                    List<WMS_TO_WCS_TASK> list = new List<WMS_TO_WCS_TASK>();
                    list.Add(task);
                    dao.InsertWMS_TO_WCS_TASKhistory(tran, list);
                    if (_resultNO < 1)
                    {
                        return new ResultModel { RESULT = "failed", MESSAGE = "泡沫箱解绑失败，请联系管理员！", DATA = null };
                    }
                }
                else
                {
                    return new ResultModel { RESULT = "failed", MESSAGE = "泡沫箱未绑定订单！", DATA = null };
                }
                _result = true;
                if (_result)
                { tran.Commit(); }
                else
                { tran.Rollback(); }
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                tran.Rollback();
                _message = ex.Message;
                _result = false;
            }
            finally
            {
                if (tran != null) tran.Dispose();
                if (cn != null) cn.Close();
                if (cn != null) cn.Dispose();
            }
            if (_result)
                return new ResultModel { RESULT = "success", MESSAGE = "泡沫箱解绑成功！", DATA = null };
            else
                return new ResultModel { RESULT = "failed", MESSAGE = "泡沫箱解绑失败！：" + _message, DATA = null };
        }

        /// <summary>
        /// 根据订单号获取订单拣货信息并绑定捡货人员
        /// </summary>
        /// <param name="OrderNO">有可能是周转箱号（补捡），或者手捡</param>
        /// <param name="UserID"></param>
        /// <param name="UserName"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        public ResultModel GetPickOrderInfoByOrderNO(string OrderNO,int UserID,string UserName, int flag = 0)
        {
            WCS_WMSDao dao = new WCS_WMSDao();
            try
            {
                //首先判断OrderNO是否为订单号(订单下发任务表)
                List<WCS_TO_WMS> AutoPicklist = dao.GetPickOrderInfoByOrderNO(OrderNO);//订单号
                if (AutoPicklist.Count <= 0)
                {
                    List<WCS_TO_WMS> AutoPicklist1 = dao.GetWCS_TO_WMSlistByBox(OrderNO);//周转箱号
                    if (AutoPicklist1.Count > 0)
                    {
                        OrderNO = AutoPicklist1[0].ORDERNO;//将扫描的泡沫箱号转换成订单号
                    }
                    else
                    { return new ResultModel { RESULT = "failed", MESSAGE = "未扫描出相关拣货信息，请查询ERP捡货任务报表，联系管理员！", DATA = null }; } 
                }
                List<WMS_APP_PICK_ORDER> lstAppPick = dao.GetPicOrderInfoByorderNO(OrderNO);
                foreach (WMS_APP_PICK_ORDER model in lstAppPick)
                {
                    if (model.FLAG == 1)
                    { return new ResultModel { RESULT = "failed", MESSAGE = "该订单已人工拣货完成，请勿重复拣货！", DATA = null }; }
                    else if (model.USERID != UserID)
                    { return new ResultModel { RESULT = "failed", MESSAGE = "该订单其他员工正在拣货，请勿重复拣货！", DATA = null }; }
                    else if (model.USERID == UserID)
                    { return new ResultModel { RESULT = "failed", MESSAGE = "该订单已处于拣货状态，请重新登录或刷新当前拣货订单信息！", DATA = null }; }
                }
                List<WCS_TO_WMS> listUnDeal = dao.GetPickOrderInfoByOrderNO(OrderNO);//获取拣货订单
                List<WMS_APP_PICK_ORDER> list = new List<WMS_APP_PICK_ORDER>();
                foreach (WCS_TO_WMS model in listUnDeal)
                {
                    if (model.FLAG == 1)
                    { return new ResultModel { RESULT = "failed", MESSAGE = "该订单已自动拣货状态，无需APP拣货！", DATA = null }; }
                    list.Add(new WMS_APP_PICK_ORDER
                    {
                        DETAILNO = model.DETAILNO,
                        ORDERNO = model.ORDERNO,
                        BOXNO = model.BOXNO,
                        AREA = model.AREA,
                        BATCH_NO = model.BATCH_NO,
                        FLAG = 0,
                        EXLOCATION = model.EXLOCATION,
                        LOCATION = model.LOCATION,
                        OTHER1 = model.OTHER1,
                        OTHER2 = model.OTHER2,
                        OTHER3 = model.OTHER3,
                        OTHER4 = model.OTHER4,
                        QTY = model.QTY,
                        PQTY = model.PQTY,
                        ITEMCODE = model.ITEMCODE,
                        ITEMNAME = model.ITEMNAME,
                        REMARK1 = model.REMARK1,
                        REMARK2 = model.REMARK2,
                        STATUS = 0,
                        PTIME = DateTime.Now,
                        BEGIN_DATE = DateTime.Now,
                        CREATE_DATE = model.CREATE_DATE,
                        FINISHTIME = model.FINISHTIME,
                        UPDATE_DATE = model.UPDATE_DATE,
                        USERID = UserID,
                        USERNAME = UserName
                    });
                }
                SaveWMS_APP_PICK_ORDER(list);//保存手机APP拣货信息，绑定拣货信息和捡货人员
                //将拣货订单绑定拣货人员
                return new ResultModel { RESULT = "success", MESSAGE = "获取订单下发捡货任务成功", DATA = listUnDeal };
            }
            catch (Exception ex)
            {
                return new ResultModel { RESULT = "failed", MESSAGE = "获取订单下发捡货任务失败：" + ex.Message, DATA = null };
            }
        }

        //手机APP绑定泡沫箱号发货
        public ResultModel SendWMStoWCStaskByApp(WMStoWCStask taskModel)
        {
            bool _result = false;
            string _message = "";
            WCS_WMSDao dao = new WCS_WMSDao();
            var oracle = new MB.RuleBase.BulkCopy.SimulatedOracleHelper();
            var db = MB.Orm.Persistence.DatabaseHelper.CreateDatabase();
            var cn = oracle.CreateOracleConnection(db.ConnectionString);
            System.Data.Common.DbTransaction tran = null;
            try
            {
                //查询泡沫箱是否已绑定
                if (taskModel.FBOXS.Count > 0)
                {
                    foreach (string item in taskModel.FBOXS)
                    {
                        WMS_TO_WCS_TASK task = dao.getWMS_TO_WCStask(item, 1);
                        if (task != null && !string.IsNullOrEmpty(task.ORDERNO))
                            return new ResultModel { RESULT = "failed", MESSAGE = string.Format("泡沫箱：{0} 已被绑定还未解绑！", item), DATA = null };
                    }
                }
                else
                {
                    return new ResultModel { RESULT = "failed", MESSAGE = string.Format("未绑定泡沫箱！"), DATA = null };
                }
                cn.Open();
                tran = cn.BeginTransaction();
                List<WCS_TO_WMS> listtmp = dao.GetWCS_TO_WMSlist(taskModel.ORDERNO, int.Parse(Consts.WCS_TO_WMS_UnDealFlag));//若有数据，说明该订单属于自动检错需要APP人工拣货
                bool IsExist = false;
                if (listtmp != null && listtmp.Count > 0) IsExist = true;

                List<WMS_APP_PICK_ORDER> list = new List<WMS_APP_PICK_ORDER>();
                string Exlocation = "";
                foreach (WCS_TO_WMS model in taskModel.WCS_TO_WMSs)
                {
                    dao.UpdateSaleItemQTY(tran, model.PQTY, model.ITEMCODE, model.ORDERNO);
                    dao.UpdateSaleItemQTY(tran, model.PTIME, model.BEGIN_DATE, model.BATCH_NO, model.LOCATION, model.ORDERNO);
                    dao.UpdateWCS_TO_WMS(tran, model.DETAILNO, model.PQTY, int.Parse(Consts.WCS_TO_WMS_DealedFlag));//将拣货完成信息里面Flag=0的订单实捡数量和Flag=1更新
                    Exlocation = model.EXLOCATION;
                    list.Add(new WMS_APP_PICK_ORDER
                    {
                        DETAILNO = model.DETAILNO,
                        ORDERNO = model.ORDERNO,
                        BOXNO = model.BOXNO,
                        AREA = model.AREA,
                        BATCH_NO = model.BATCH_NO,
                        FLAG = 1,
                        EXLOCATION = model.EXLOCATION,
                        LOCATION = model.LOCATION,
                        OTHER1 = model.OTHER1,
                        OTHER2 = model.OTHER2,
                        OTHER3 = model.OTHER3,
                        OTHER4 = model.OTHER4,
                        QTY = model.QTY,
                        PQTY = model.PQTY,
                        ITEMCODE = model.ITEMCODE,
                        ITEMNAME = model.ITEMNAME,
                        REMARK1 = model.REMARK1,
                        REMARK2 = model.REMARK2,
                        STATUS = model.STATUS,
                        PTIME = model.PTIME,
                        BEGIN_DATE = model.BEGIN_DATE,
                        CREATE_DATE = model.CREATE_DATE,
                        FINISHTIME = model.FINISHTIME,
                        UPDATE_DATE = model.UPDATE_DATE,
                        USERID = taskModel.USERID,
                        USERNAME = taskModel.USERNAME
                    });
                }
                dao.InsertWMS_APP_PICK_ORDER(tran, list);//保存APP订单拣货信息
                if (IsExist)
                {
                    dao.InsertWCSTOWMShistory(tran, taskModel.WCS_TO_WMSs);//自动拣货补捡的订单信息手机拣货后保存历史
                }
                List<WMS_TO_WCS_TASK> tasklist = new List<WMS_TO_WCS_TASK>();
                foreach (string item in taskModel.FBOXS)
                {
                    tasklist.Add(new WMS_TO_WCS_TASK {  ORDERNO = taskModel.ORDERNO, FBOXNO = item, EXLOCATION = Exlocation, OTHER1 = Consts.WCS_TO_WMS_DealedFlag, STATUS = 0, CREATERID = taskModel.USERID, CREATER = taskModel.USERNAME,CREATE_DATE=DateTime.Now });
                }
                dao.SendWMS_TO_WCStask(tran, tasklist);//绑定发货箱信息
                _result = true;
                if (_result)
                {
                    tran.Commit();
                }
                else
                {
                    tran.Rollback();
                }
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                _message = ex.Message;
                tran.Rollback();
                _result = false;
            }
            finally
            {
                if (tran != null) tran.Dispose();
                if (cn != null) cn.Close();
                if (cn != null) cn.Dispose();
            }
            if (_result)
                return new ResultModel { RESULT = "success", MESSAGE = "手工拣货并下发泡沫箱任务！", DATA = null };
            else
                return new ResultModel { RESULT = "failed", MESSAGE = "手工拣货并下发泡沫箱任务失败！：" + _message, DATA = null };
        }

        //暂时保存手机APP拣货信息
        public ResultModel SaveWMS_APP_PICK_ORDER(List<WMS_APP_PICK_ORDER> list)
        {
            bool _result = false;
            string _message = "";
            WCS_WMSDao dao = new WCS_WMSDao();
            var oracle = new MB.RuleBase.BulkCopy.SimulatedOracleHelper();
            var db = MB.Orm.Persistence.DatabaseHelper.CreateDatabase();
            var cn = oracle.CreateOracleConnection(db.ConnectionString);
            System.Data.Common.DbTransaction tran = null;
            try
            {
                cn.Open();
                tran = cn.BeginTransaction();
                _result = dao.InsertWMS_APP_PICK_ORDER(tran, list);//保存APP订单拣货信息
                if (_result)
                {tran.Commit();}
                else
                {tran.Rollback();}
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                _message = ex.Message;
                tran.Rollback();
                _result = false;
            }
            finally
            {
                if (tran != null) tran.Dispose();
                if (cn != null) cn.Close();
                if (cn != null) cn.Dispose();
            }
            if (_result)
                return new ResultModel { RESULT = "success", MESSAGE = "手工APP拣货信息暂时保存任务成功！", DATA = null };
            else
                return new ResultModel { RESULT = "failed", MESSAGE = "手工APP拣货信息暂时保存任务失败！：" + _message, DATA = null };
        }

        //根据当前登录用户ID获取该用户未完成订单信息（按订单编号排序，多商品）
        public ResultModel GetPickOrderInfoByUserID(int UserId, int Flag = 0)
        {
            WCS_WMSDao dao = new WCS_WMSDao();
            try
            {
                List<WMS_APP_PICK_ORDER> listUnDeal = dao.GetPicOrderInfoByUserId(UserId, Flag);
                Dictionary<string, List<WMS_APP_PICK_ORDER>> OrderList = new Dictionary<string, List<WMS_APP_PICK_ORDER>>();
                foreach (WMS_APP_PICK_ORDER model in listUnDeal)
                {
                    if (OrderList.ContainsKey(model.ORDERNO.Trim()))
                    {
                        OrderList[model.ORDERNO.Trim()].Add(model);
                    }
                    else
                    {
                        List<WMS_APP_PICK_ORDER> lis = new List<WMS_APP_PICK_ORDER>();
                        lis.Add(model);
                        OrderList.Add(model.ORDERNO.Trim(), lis);
                    }
                }
                List<stuOrderList> ListBase = new List<stuOrderList>();
                foreach (var item in OrderList)
                {
                    stuOrderList order = new stuOrderList();
                    order.OrderNO = item.Key;
                    order.OrderList = item.Value;
                    ListBase.Add(order);
                }
                //string JsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(ListBase);
                if (ListBase == null || ListBase.Count <= 0)
                {
                    return new ResultModel { RESULT = "failed", MESSAGE = "未获取到该用户有关的未完成拣货信息", DATA =null  };
                }
                else
                {
                    return new ResultModel { RESULT = "success", MESSAGE = "获取订单下发捡货任务成功", DATA = ListBase };
                }
            }
            catch (Exception ex)
            {
                return new ResultModel { RESULT = "failed", MESSAGE = "获取订单下发捡货任务失败：" + ex.Message, DATA = null };
            }
        }

        public List<stuOrderList> IsExistOrder(List<stuOrderList> ListBase, WMS_APP_PICK_ORDER model)
        {
            if (ListBase.Count <= 0)
            {
                stuOrderList struAdd = new stuOrderList();
                struAdd.OrderNO = model.ORDERNO.Trim();
                List<WMS_APP_PICK_ORDER> lis = struAdd.OrderList == null ? new List<WMS_APP_PICK_ORDER>(): struAdd.OrderList;
                lis.Add(model);
            }
            else
            {
                foreach (stuOrderList stru in ListBase)
                {
                    if (stru.OrderNO.Trim().Equals(model.ORDERNO.Trim()))
                    {
                        stru.OrderList.Add(model);
                    }
                    else
                    {
                        stuOrderList struAdd = new stuOrderList();
                        struAdd.OrderNO = model.ORDERNO.Trim();
                        struAdd.OrderList.Add(model);
                    }
                }
            }
            return ListBase;
        }
    }
}
